package com.ndp.fb.walle.controller;

import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.exception.BusinessException;
import com.ndp.fb.exception.ErrorCode;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.redis.api.RedisClient;
import com.ndp.fb.walle.business.FBOauthService;
import com.ndp.fb.walle.util.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * facebook授权
 * Created by Mikey.zhaopeng on 2014/10/24 15:32.
 * Email mikey.zhao@ndpmedia.com
 */
@RequestMapping("/fboauth")
@Controller
public class FBOauthController {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private FBOauthService fbOauthService;
    @Autowired
    private RedisClient redisClient;


    @RequestMapping(value = "/getCode", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String getCode(HttpServletRequest request) {
        ErrorType errorType = null;
        String redirectUrl = fbOauthService.getRedirectUrl("");
        String userId = getUserId(request);
        String flag = CommonConstants.USER_ADD_FLAG + userId;
        if (!redisClient.setNx(flag, userId)) {
            //正在添加BussinessManager账号
            try {
                throw new BusinessException(ErrorCode.ERROR_60019);
            } catch (BusinessException e) {
                errorType = e.getErrorType();
                logger.error(e.getMessage(), e);
            }
        } else {
            try {
                redisClient.expire(flag, 1, TimeUnit.HOURS.name());
                Boolean isNotExists = fbOauthService.isCanAddFbUser(userId);//是否已经存在关联了用户
                if (isNotExists) {
                    //3.添加正在添加账号标识
                    fbOauthService.addFbUser(request.getParameter("code"), request.getParameter("error_code"), request.getParameter("error_message"), userId);
                }else {
                    fbOauthService.updateFbUser(request.getParameter("code"), request.getParameter("error_code"), request.getParameter("error_message"), userId);
                }
            } catch (BusinessException e) {
                errorType = e.getErrorType();
                logger.error(e.getMessage(), e);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                redisClient.delete(flag);
            }
        }
        StringBuffer js = new StringBuffer();
        js.append("<script>");

        if (null != errorType) {
            js.append("alert('").append(ResponseUtils.getMsg(errorType)).append("');");
        }
        js.append("window.location.href='").append(redirectUrl).append("';");
        js.append("</script>");

        return js.toString();

    }

    private String getUserId(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        return user.getTicket() + "";
    }
}
